import React, { createContext, useContext, useEffect, useReducer } from 'react';
import { getCartFromStorage, saveCartToStorage } from '../utils/storage';

// 初始状态:购物车数据为空
const initialState = {
  cartItems: [],
};

// Reducer函数
function cartReducer(state, action) {
  switch (action.type) {
    case 'SET_CART':
      return { ...state, cartItems: action.payload };
    case 'ADD_ITEM':
      return {
        ...state,
        cartItems: state.cartItems.some(item => item.id === action.payload.id)
          ? state.cartItems.map(item => 
              item.id === action.payload.id
                ? { ...item, quantity: item.quantity + action.payload.quantity }
                : item
            )
          : [...state.cartItems, action.payload]
      };
    case 'UPDATE_QUANTITY':
      return {
        ...state,
        cartItems: state.cartItems.map(item =>
          item.id === action.payload.id
            ? { ...item, quantity: action.payload.quantity }
            : item
        )
      };
    case 'REMOVE_ITEM':
      return {
        ...state,
        cartItems: state.cartItems.filter(item => item.id !== action.payload)
      };
    case 'CLEAR_CART':
      return { ...state, cartItems: [] };
    default:
      return state;
  }
}

const CartContext = createContext();

export const CartProvider = ({ children }) => {
  const [state, dispatch] = useReducer(cartReducer, initialState);

  // 初始化购物车
  useEffect(() => {
    //getCartFromStorage来自utils/storage.js
    const storedCart = getCartFromStorage();//从 localStorage 读取
    if (storedCart && storedCart.length > 0) {
      dispatch({ type: 'SET_CART', payload: storedCart });//// 初始化状态
    }
  }, []);

  // 当购物车变化时保存到localStorage
  useEffect(() => {
    if (state.cartItems.length > 0) {
      saveCartToStorage(state.cartItems);
    } else {
      localStorage.removeItem('cart');
    }
  }, [state.cartItems]);

  // 添加商品到购物车
  const addToCart = (item) => {
    dispatch({ type: 'ADD_ITEM', payload: item });
  };

  // 更新商品数量
  const updateQuantity = (id, quantity) => {
    dispatch({ type: 'UPDATE_QUANTITY', payload: { id, quantity } });
  };

  // 移除商品
  const removeItem = (id) => {
    dispatch({ type: 'REMOVE_ITEM', payload: id });
  };

  // 清空购物车
  const clearCart = () => {
    dispatch({ type: 'CLEAR_CART' });
  };

  return (
    <CartContext.Provider
      value={{
        cartItems: state.cartItems,
        addToCart,
        updateQuantity,
        removeItem,
        clearCart,
      }}
    >
      {children}
    </CartContext.Provider>
  );
};

export const useCart = () => useContext(CartContext);